
package com.epam.android.training.level1.activity;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.db.dao.PollDao;
import com.epam.android.training.level1.db.dao.impl.PollDaoImpl;
import com.epam.android.training.level1.poll.AnswerBo;
import com.epam.android.training.level1.poll.QuestionBo;
import com.epam.android.training.level1.widget.CollectionAdapter;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import java.util.List;

/**
 * @author Anton Novikau
 */
public class SinglePollActivity extends BasePageActivity {

  private ViewFlipper wizard;

  private int wizardSize;

  private Button nextButton;

  private Button backButton;

  private LayoutInflater inflater;

  private ProgressDialog progress;

  private PollDao pollDao;

  private List<QuestionBo> questions;

  private long pollId;

  private int result;

  private int currentPosition;

  private boolean isLast;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.poll_wizard);

    inflater = getLayoutInflater();

    pollDao = new PollDaoImpl(this);

    wizard = (ViewFlipper) findViewById(R.id.poll_container);
    nextButton = (Button) findViewById(R.id.next_button);
    backButton = (Button) findViewById(R.id.back_button);

    Intent intent = getIntent();
    pollId = intent.getLongExtra(POLL_ID_EXTRA, -1);
    new QuestionRetreiveTask().execute(pollId);

    addBackButtonAction();
    addNextButtonAction();
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    // TODO: investigate how to change orientation correctly.
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
      case R.id.questions_fetch_progress:
        progress = new ProgressDialog(this);
        progress.setMessage(getText(R.string.loading_message));
        return progress;
      case R.id.poll_results:
        final Dialog showResults = new Dialog(this);
        showResults.setCancelable(false);
        showResults.setContentView(R.layout.result_dialog);
        showResults.setTitle(R.string.poll_result_title);
        TextView resultsView = (TextView) showResults.findViewById(R.id.poll_result);
        resultsView.setText(getString(R.string.poll_result_text, result));
        TextView totalQuestionsView = (TextView) showResults.findViewById(R.id.total_questions);
        totalQuestionsView.setText(String.valueOf(wizardSize));
        Button okButton = (Button) showResults.findViewById(R.id.ok_button);
        okButton.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
            showResults.dismiss();
            Intent data = new Intent();
            data.putExtra(POLL_ID_EXTRA, pollId);
            data.putExtra(POLL_RESULT_EXTRA, result);
            setResult(RESULT_OK, data);
            finish();
          }
        });
        return showResults;
      default:
        return super.onCreateDialog(id);
    }

  }

  private void addNextButtonAction() {
    nextButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        if (isLast) {
          result = calculatePollResults();
          pollDao.savePollResult(pollId, result);
          showDialog(R.id.poll_results);
        } else {
          currentPosition++;
          // check if next item is the last one and set new label to button.
          isLast = currentPosition + 1 == wizardSize;
          if (isLast) {
            nextButton.setText(R.string.finish_button);
          }

          if (currentPosition > 0) {
            backButton.setEnabled(true);
          }

          wizard.showNext();
        }
      }
    });
  }

  private void addBackButtonAction() {

    backButton.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        isLast = false;
        if (currentPosition > 0) {
          currentPosition--;
          nextButton.setText(R.string.next_button);
          // check if previous item is the first one and disable the button.
          backButton.setEnabled(currentPosition > 0);
          wizard.showPrevious();
        }
      }
    });
  }

  private void inflateWizardItems(List<QuestionBo> questions) {
    if (questions.isEmpty()) {
      return;
    }

    for (QuestionBo question : questions) {
      View body = inflater.inflate(R.layout.poll_body, wizard, false);
      TextView questionView = (TextView) body.findViewById(R.id.question_area);
      ListView answerContainer = (ListView) body.findViewById(R.id.answers_contaier);

      questionView.setText(question.getDisplayName());
      answerContainer.setAdapter(new AnswersAdapter(question.getAnswers()));
      wizard.addView(body);
    }

    wizardSize = wizard.getChildCount();
  }

  private int calculatePollResults() {
    int answerRaiting = 0;
    for (int i = 0; i < wizardSize; i++) {
      QuestionBo question = questions.get(i);
      List<AnswerBo> answers = question.getAnswers();
      // int actualCorrect = question.getCorrectAnswers();
      View wizardItem = wizard.getChildAt(i);
      ListView answerContainer = (ListView) wizardItem.findViewById(R.id.answers_contaier);
      int answersSize = answerContainer.getChildCount();

      int correct = answersSize;
      for (int j = 0; j < answersSize; j++) {
        View answerView = answerContainer.getChildAt(j);
        CheckBox answerBox = (CheckBox) answerView.findViewById(R.id.answer);
        AnswerBo answer = answers.get(j);
        if ((!answerBox.isChecked() && answer.isCorrect())
            || (answerBox.isChecked() && !answer.isCorrect())) {
          correct--;
        }
      }
      answerRaiting += correct * 100 / answersSize;
    }
    return answerRaiting / wizardSize;
  }

  private class AnswersAdapter extends CollectionAdapter<AnswerBo> {

    public AnswersAdapter(List<AnswerBo> items) {
      super(items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      CheckBox answerView;
      if (convertView == null) {
        convertView = inflater.inflate(R.layout.answer_item, parent, false);
        answerView = (CheckBox) convertView.findViewById(R.id.answer);
        convertView.setTag(answerView);
      } else {
        answerView = (CheckBox) convertView.getTag();
      }

      AnswerBo answer = getItem(position);
      answerView.setText(answer.getDisplayName());

      return convertView;
    }
  }

  private class QuestionRetreiveTask extends AsyncTask<Long, Void, List<QuestionBo>> {

    @Override
    protected List<QuestionBo> doInBackground(Long... params) {
      return pollDao.findQuestions(params[0]);
    }

    @Override
    protected void onPreExecute() {
      showDialog(R.id.questions_fetch_progress);
    }

    @Override
    protected void onPostExecute(List<QuestionBo> result) {
      inflateWizardItems(result);
      questions = result;
      progress.dismiss();
    }
  }
}
